package com.jianyun.jyzs.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.presenter.FlowDetailPresenter;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.IFlowDetailView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jianyun.jyzs.activity.FlowExamineHtmlActivity.shenPiRefreshYes;

/**
 * 流程审批详情界面
 * Created by yangshijun on 2018/7/16.
 */

public class FlowExamineDetailActivity extends MvpActivity<IFlowDetailView, FlowDetailPresenter> implements IFlowDetailView {

    @BindView(R.id.nullNetWork)
    LinearLayout nullNetWork;
    @BindView(R.id.webview)
    WebView webview;

    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.imgbtn_custom_nav_finish)
    ImageButton imgbtnCustomNavFinish;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    private String url;
    private boolean askedgalleryPermission = false;
    private int galleryPermissionReqCode = 202;
    public WebSettings webSettings;
    private int height;
    public boolean isRefreshSuccess=false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_workflow_detail);
        ButterKnife.bind(this);
        url = getIntent().getStringExtra("url");
        initView();
        initData();
    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        topText.setText(R.string.top_workFlow_app);
        ivMoreLinearLayout.setVisibility(View.VISIBLE);
        ivMore.setVisibility(View.VISIBLE);
        ivMore.setImageResource(R.drawable.flow_detail);
        imgbtnCustomNavFinish.setVisibility(View.VISIBLE);
    }


    @NonNull
    @Override
    public FlowDetailPresenter createPresenter() {
        return new FlowDetailPresenter();
    }

    protected void initData() {
        webSettings = webview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //放开storage缓存机制
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(new JavaScriptObject(), "control");//传递对象进行交互
        webview.setDownloadListener(new MyWebViewDownLoadListener());
        webview.setWebViewClient(new webViewClient());
        webview.setWebChromeClient(new OAWebChromeClient());
        webview.loadUrl(url);

        Log.i("test", "详情：" + url);


    }

    public class JavaScriptObject {


        @JavascriptInterface
        public void refreshHtml() {
            Log.i("test", "审批刷新");
            isRefreshSuccess=true;
        }

        @JavascriptInterface
        public void finishActivity() {
            Log.i("test", "关闭");
            Intent intent = new Intent();
            intent.putExtra("isRefresh",isRefreshSuccess) ;
            if (isRefreshSuccess){
                setResult(shenPiRefreshYes,intent);
            }
            FlowExamineDetailActivity.this.finish();
        }

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        height = webview.getMeasuredHeight();

        Log.i("test", "高度：" + height);
    }

    //Web视图
    private class webViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//网页页面开始加载的时候
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//	         //页面下载完毕,却不代表页面渲染完毕显示出来
//            if (webview.getContentHeight() != 0) { //这个时候网页才显示
            progressBar.setVisibility(View.INVISIBLE);
//            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("test", "加载2：" + url);
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
//            if (url.endsWith("isDowload=yes")) {

            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            view.loadUrl("file:///android_asset/error.html");
        }
    }


    public class OAWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (topText != null && !TextUtils.isEmpty(title)) {
                topText.setText(title);
                if ("我的待办流程".equals(title)) {
                    isRefreshSuccess=true;
                    //隐藏
                    ivMore.setVisibility(View.INVISIBLE);
                } else {
                    ivMore.setVisibility(View.VISIBLE);
                }
                Log.i("test", "title:" + title);
            }
        }


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            //Log.i("test", "onProgressChanged高度：");
            //编写 javaScript方法
            String javascript2 = "javascript:function hideOther() {" +
                    "document.getElementsByClassName('head')[0].style.display='none';" +
                    "}";
            String javaScript = "javascript:function setBodyHeight(){" +
                    "document.getElementsByTagName('body')[0].style.height=600+'px';" +
                    "}";


            //创建方法
//            view.loadUrl(javascript2);
//            //加载方法
//            view.loadUrl("javascript:hideOther();");
//
//
//            view.loadUrl(javaScript);
//            view.loadUrl("javascript:setBodyHeight();");

//            String javaScript3 = "javascript:webviewHeight" + "(" + height + ")";
//            view.loadUrl(javaScript3);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }


    @OnClick({R.id.topBack, R.id.iv_more, R.id.imgbtn_custom_nav_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                Intent intent = new Intent();
                intent.putExtra("isRefresh",isRefreshSuccess) ;
                if (isRefreshSuccess){
                    setResult(shenPiRefreshYes,intent);
                }
                finish();
                break;
            case R.id.iv_more:
                webview.loadUrl("javascript:showPic()");
                break;
            case R.id.imgbtn_custom_nav_finish:
                Intent intent2 = new Intent();
                intent2.putExtra("isRefresh",isRefreshSuccess) ;
                if (isRefreshSuccess){
                    setResult(shenPiRefreshYes,intent2);
                }
                finish();
                break;

        }
    }


    /**
     * webview点击下载
     */
    class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            showFile(url);
        }

    }

    public void showFile(String url) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //有权限
            //其他手机 下载 打开
            startActivity((new Intent(this, ShowFileActivity.class))
                    .putExtra("type", -1)
                    .putExtra("id", -1)
                    .putExtra("folderID", "workFlow")
                    .putExtra("remotepath", url));
        } else if (!askedgalleryPermission) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    galleryPermissionReqCode);
            askedgalleryPermission = true;
        }
    }

}
